//
//  WPAudioPlayController.m
//  wobingwoyi
//
//  Created by WGP on 2016/11/24.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPAudioPlayController.h"
#import <AVFoundation/AVFoundation.h>

@interface WPAudioPlayController ()<AVAudioPlayerDelegate>

@property (nonatomic,strong) AVAudioPlayer *audioPlayer;//播放器

@property(nonatomic,strong)UIButton *backBtn;
@property(nonatomic,strong)UILabel *timeLabel;
@property(nonatomic,strong)UIButton *deleteBtn;
@property(nonatomic,strong)UIButton *playOrPause;

@property (weak ,nonatomic) NSTimer *timer;//进度更新定时器

@end

@implementation WPAudioPlayController

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [self.timer invalidate];
    self.timer = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.view.backgroundColor = RGB_COLOR(31, 33, 36);
    [self setupUI];
}

-(void)setupUI
{
    [self backBtn];
    [self timeLabel];
    [self deleteBtn];
    [self playOrPause];
}

-(NSTimer *)timer
{
    if (!_timer)
    {
        _timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];
    }
    return _timer;
}

-(AVAudioPlayer *)audioPlayer
{
    if (!_audioPlayer)
    {
        NSError *error=nil;
        //初始化播放器，注意这里的Url参数只能时文件路径，不支持HTTP Url
        _audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:self.url error:&error];
        //设置播放器属性
        _audioPlayer.numberOfLoops=0;//设置为0不循环
        _audioPlayer.delegate=self;
        [_audioPlayer prepareToPlay];//加载音频文件到缓存
        if(error)
        {
            NSLog(@"初始化播放器过程发生错误,错误信息:%@",error.localizedDescription);
            return nil;
        }
    }
    return _audioPlayer;
}

-(UIButton *)backBtn
{
    if (_backBtn == nil)
    {
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backBtn setTitle:@"    " forState:UIControlStateNormal];
        [_backBtn setImage:[UIImage imageNamed:@"audio_back"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backBtnDidClick) forControlEvents:UIControlEventTouchDown];
        [self.view addSubview:_backBtn];
        
        [_backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).offset(15);
            make.top.equalTo(self.view).offset(30);
            make.height.mas_equalTo(30);
        }];
    }
    return _backBtn;
}

-(UILabel *)timeLabel
{
    if (_timeLabel == nil)
    {
        _timeLabel = [UILabel new];
        _timeLabel.textColor = [UIColor whiteColor];
        _timeLabel.font = [UIFont systemFontOfSize:18];
        _timeLabel.textAlignment = NSTextAlignmentRight;
        _timeLabel.text = @"00:00/00:00";
        [self.view addSubview:_timeLabel];
        
        [_timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.backBtn);
            make.right.equalTo(self.view).offset(-15);
        }];
    }
    return _timeLabel;
}

-(UIButton *)deleteBtn
{
    if (_deleteBtn == nil)
    {
        _deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_deleteBtn setBackgroundImage:[UIImage imageNamed:@"delete_normal"] forState:UIControlStateNormal];
        [_deleteBtn addTarget:self action:@selector(deleteBtnDidClick) forControlEvents:UIControlEventTouchDown];
        [self.view addSubview:_deleteBtn];
        
        [_deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.view).offset(-25);
            make.bottom.equalTo(self.view).offset(-35);
        }];
    }
    return _deleteBtn;
}

-(UIButton *)playOrPause
{
    if (_playOrPause == nil)
    {
        _playOrPause = [UIButton buttonWithType:UIButtonTypeCustom];
        [_playOrPause setBackgroundImage:[UIImage imageNamed:@"audio_play"] forState:UIControlStateNormal];
        //        [_playOrPause setBackgroundImage:[UIImage imageNamed:@"audio_stop"] forState:UIControlStateNormal];
        [_playOrPause addTarget:self action:@selector(playOrPauseBtnDidClick:) forControlEvents:UIControlEventTouchDown];
        [self.view addSubview:_playOrPause];
        
        [_playOrPause mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.view);
        }];
        
    }
    return _playOrPause;
}
#pragma mark - 按钮响应事件
-(void)playOrPauseBtnDidClick:(UIButton *)btn
{
    if (![self.audioPlayer isPlaying])
    {
        [self.audioPlayer play];
        [btn setBackgroundImage:nil forState:UIControlStateNormal];
        self.timer.fireDate=[NSDate distantPast];//恢复定时器
    }
    else
    {
        [self.audioPlayer pause];
        [btn setBackgroundImage:[UIImage imageNamed:@"audio_play"] forState:UIControlStateNormal];
        self.timer.fireDate=[NSDate distantFuture];//暂停定时器，注意不能调用invalidate方法，此方法会取消，之后无法恢复
    }
}

/**
 *  更新播放进度
 */
-(void)updateProgress
{
    float currentTime= self.audioPlayer.currentTime ;
    float totalTime = self.audioPlayer.duration;
    
    self.timeLabel.text = [NSString stringWithFormat:@"%@/%@",[NSString timeStrWithDurations:currentTime],[NSString timeStrWithDurations:totalTime]];
}

-(void)backBtnDidClick
{
    [self.timer invalidate];
    self.timer = nil;
    
    if (self.backBlock)
    {
        self.backBlock();
    }
}

-(void)deleteBtnDidClick
{
    if([self.audioPlayer isPlaying])
    {
        [self.audioPlayer pause];
        [self.playOrPause setBackgroundImage:[UIImage imageNamed:@"audio_play"] forState:UIControlStateNormal];
        self.timer.fireDate=[NSDate distantFuture];//暂停定时器，注意不能调用invalidate方法，此方法会取消，之后无法恢复
    }
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"确定要清除吗?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        if (self.deleteBlock)
        {
            self.deleteBlock(self.index);
        }
    }];
    [alertController addAction:cancel];
    [alertController addAction:sure];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - 播放器代理方法
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [self.audioPlayer pause];
    [self.playOrPause setBackgroundImage:[UIImage imageNamed:@"audio_play"] forState:UIControlStateNormal];
}

-(void)dealloc
{
    WPLog(@"WPAudioPlayController 死了");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
